/**
 * Socket客户端管理模块
 */
class SocketClient {
    constructor() {
        this.socket = null;
        this.isConnected = false;
        this.eventHandlers = {};
        this.init();
    }

    init() {
        this.socket = io();
        this.setupEventListeners();
    }

    setupEventListeners() {
        this.socket.on('connect', () => {
            this.isConnected = true;
            this.emit('socketConnect');
            console.log('已连接到服务器');
        });

        this.socket.on('disconnect', () => {
            this.isConnected = false;
            this.emit('socketDisconnect');
            console.log('与服务器断开连接');
        });

        this.socket.on('connection_result', (data) => {
            console.log('连接结果:', data);
            this.emit('connectionResult', data);
        });

        this.socket.on('event_result', (data) => {
            console.log('连接结果:', data);
            this.emit('eventResult', data);
        });
    }

    // 发送登录请求
    loginRemote(config) {
        if (!this.isConnected) {
            console.error('Socket未连接');
            return;
        }
        this.socket.emit('login_remote', config);
    }

    // 发送命令事件
    sendCommand(config) {
        if (!this.isConnected) {
            console.error('Socket未连接');
            return;
        }
        this.socket.emit('command_event', config);
    }

    // 事件监听
    on(event, handler) {
        if (!this.eventHandlers[event]) {
            this.eventHandlers[event] = [];
        }
        this.eventHandlers[event].push(handler);
    }

    // 触发事件
    emit(event, data) {
        if (this.eventHandlers[event]) {
            this.eventHandlers[event].forEach(handler => handler(data));
        }
    }

    // 移除事件监听
    off(event, handler) {
        if (this.eventHandlers[event]) {
            this.eventHandlers[event] = this.eventHandlers[event].filter(h => h !== handler);
        }
    }
}

// 创建全局Socket客户端实例
window.socketClient = new SocketClient();